#include "objectsloader.h"

ObjectsLoader ObjectsLoader::instance;

ObjectsLoader::ObjectsLoader(){ }

ObjectsLoader::ObjectsLoader(const ObjectsLoader& instantiator){ }

void ObjectsLoader::scanConfigs()
{
    AppSettings& appSettings = AppSettings::getInstance();

    QString configPath = appSettings.configPath +
                         QDir::separator() +
                         appSettings.ELEMENTS_PATH_NAME;
    QDir elementsDir(configPath);
    QStringList files = elementsDir.entryList(QStringList("*.xml"), QDir::Files);
    for (int i =0; i < files.size(); i++)
    {
        QString fileName = elementsDir.absoluteFilePath(files.at(i));
        QFile file(fileName);

        if (file.open(QIODevice::ReadOnly))
        {
            QDomDocument domDoc;
            domDoc.setContent(&file);
            QDomNode root = domDoc.namedItem("root");
            QString alias = root.attributes().namedItem("alias").nodeValue();

            ObjectConfig config;
            config.category = root.attributes().namedItem("category").nodeValue();
            config.className = root.attributes().namedItem("class").nodeValue();
            config.fileName = fileName;

            this->objects.insert(alias,config);
            file.close();
        }
    }
}

ObjectConfig ObjectsLoader::getConfig(QString alias)
{
    return ObjectsLoader::objects.value(alias);
}

QString ObjectsLoader::getConfigPath(QString className)
{
    QMap<QString, ObjectConfig>::const_iterator i;
    for (i = objects.constBegin(); i != objects.constEnd(); i++)
    {
        if (i.value().className == className)
            return i.value().fileName;
    }
    return "";
}

QMap<QString,ObjectConfig>& ObjectsLoader::getConfigs(){
    return ObjectsLoader::objects;
}

ObjectsLoader& ObjectsLoader::getInstance()
{
    return ObjectsLoader::instance;
}
